package com.yonyou.pmclouds.milestone.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.impl.NCBillTypeQueryService;
import com.yonyou.pmclouds.billtype.entity.BillTypeRefVO;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author th
 * @date 2019/11/6 19:26
 */
@Service(interfaceClass = IBillTypeRefService.class, version = ApplicationConsts.APPLICATION_VERSION)
public class BillTypeRefServiceImpl implements IBillTypeRefService {
    @Autowired
    private NCBillTypeQueryService ncBillTypeQueryIService;
    @Autowired
    private ProjectSimpleQuery projectSimpleQuery;

    /**
     * 友工程单据类型
     */
    private static Map<String, String> pmcBillTypeMap = new HashMap<>();

    static {
        pmcBillTypeMap.put(BillTypeConst.WORKSTART_BILLTYPE, BillTypeConst.WORKSTART_BILLTYPE_NAME);
        pmcBillTypeMap.put(BillTypeConst.COMPREHENSIVE_ACCEPTANCE_BILLTYPE,
                BillTypeConst.COMPREHENSIVE_ACCEPTANCE_BILLTYPE_NAME);
    }

    @Override
    public List<BillTypeRefVO> getBillTypeRefList(String pkProject) throws BusinessException {
        List<BillTypeRefVO> billTypeRefVOList = new ArrayList<>();

        // 分别从友工程、NC获取里程碑需要关联的单据类型
        addBillTypeFromPMC(billTypeRefVOList);
        addBillTypeFromNC(billTypeRefVOList, pkProject);

        return billTypeRefVOList;
    }

    /**
     * 添加NC的单据类型
     *
     * @param billTypeRefVOList
     * @param pkProject
     */
    private void addBillTypeFromNC(List<BillTypeRefVO> billTypeRefVOList, String pkProject) throws BusinessException {
        // pkProject可能为空
        if (StringUtils.isNotEmpty(pkProject)) {
            ProjectVO project = projectSimpleQuery.queryProject(pkProject);
            if (project == null)
                return;

            // 非nc项目不需要查询
            if (StringUtils.isEmpty(project.getPkSrc())) {
                return;
            }
        }

        BillTypeRefVO[] billTypeRefVOs = ncBillTypeQueryIService.queryRelatedBillTypeForPlan();
        if (ArrayUtils.isEmpty(billTypeRefVOs))
            return;

        billTypeRefVOList.addAll(Arrays.asList(billTypeRefVOs));
    }

    /**
     * 添加友工程的单据类型
     *
     * @param billTypeRefVOList
     */
    private void addBillTypeFromPMC(List<BillTypeRefVO> billTypeRefVOList) {
        for (Map.Entry<String, String> entry : pmcBillTypeMap.entrySet()) {
            billTypeRefVOList.add(new BillTypeRefVO(entry.getKey(), entry.getValue()));
        }
    }
}
